/**
 * Created by fangshufeng on 2018/1/9.
 */

import  React from 'react';
import io from 'socket.io-client'

import QRCode from 'qrcode.react'

import {
    Modal, Menu, Icon, Form, Input, Row, Col,
    Button, Checkbox, Select
} from 'antd';

import  {SuccessModal, ErrorModalAutoDismiss, SucceedModalAutoDismiss, InfoModal} from './AlertManage';

import jsonFormat from  'json-format';

const SubMenu = Menu.SubMenu;
const FormItem = Form.Item;
const {TextArea} = Input;
const Option = Select.Option;

const Domain = 'http://192.168.32.209:7778';

const envObj = {
    stb1: 'http://192.168.3.79:19000/',
    stb2: 'http://192.168.3.69:19000/',
    stb3: 'http://192.168.3.70:19000/',
    stb4: 'http://192.168.3.103:19000/',
    stb5: 'http://192.168.3.71:19000/',
    stb6: 'http://192.168.3.100:19000/',
    stb7: 'http://192.168.3.36:19000/',
    sit: 'https://m.sit.nonobank.com/feserver/',
    pre: 'https://m.pre.nonobank.com/feserver/',
    pro: 'https://m.nonobank.com/feserver/',
};

class RightDetail extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            isMock: props.dataSource.isMock
        }
    }

    mockValue = () => {
        try {
            let value = this.refs.result.textAreaRef.value;
            // JSON.parse(value);
            return JSON.parse(value)
        } catch (e) {
            return undefined;
        }

    };

    responDefaultValue = () => {
        try {
            return jsonFormat(this.props.dataSource.data, {
                type: 'space',
                size: 2
            });
        } catch (e) {
            return this.props.dataSource.data;
        }

    };

    render() {
        const formItemLayout = {
            labelCol: {span: 4},
            wrapperCol: {span: 14},
        };

        return ( <div>

                <Form layout="horizontal">
                    <FormItem
                        label="请求地址"
                        {...formItemLayout}
                    >
                    <TextArea
                        value={this.props.dataSource.config.url}
                        autosize={true}
                    />
                    </FormItem>


                    <FormItem
                        label="请求方式"
                        {...formItemLayout}
                    >
                    <TextArea
                        value={this.props.dataSource.config.method }
                        autosize={true}
                    />
                    </FormItem>


                    <FormItem
                        label="请求参数"
                        {...formItemLayout}
                    >
                    <TextArea
                        value={jsonFormat(JSON.parse(this.props.dataSource.config.data), {
                            type: 'space',
                            size: 2
                        }) }
                        autosize={true}/>
                    </FormItem>

                    <Row type='flex' justify='start'>
                        <Col span={24}>
                            <FormItem
                                label="请求结果"
                                {...formItemLayout}
                            >
                                <div key={this.props.dataSource.config.url}>
                            <TextArea
                                ref="result"
                                type="text"
                                defaultValue={this.responDefaultValue()}
                                autosize={true}
                            />
                                </div>
                            </FormItem>
                        </Col>

                    </Row>

                    <Row type='flex' justify='center'>
                        <Col span={4}>
                            <FormItem
                                {...formItemLayout}
                            >
                                <Checkbox
                                    checked={this.state.isMock}
                                    onChange={
                                        (e) => {
                                            this.setState({
                                                isMock: !this.state.isMock
                                            });
                                            if (this.state.isMock) {
                                                this.props.mockAction({
                                                    mockKey: this.props.dataSource.config.urlIdentification,
                                                    mockValue: this.mockValue()
                                                }, false)
                                            }
                                        }}>mock</Checkbox>
                            </FormItem>

                        </Col>

                        <Col span={4}>
                            <Button
                                disabled={!this.state.isMock}
                                onClick={() => {
                                    this.props.mockAction({
                                        mockKey: this.props.dataSource.config.urlIdentification,
                                        mockValue: this.mockValue()
                                    }, true)
                                }}
                            >确认修改</Button>
                        </Col>
                    </Row>

                    <FormItem
                        label="请求头信息"
                        {...formItemLayout}
                    >
                    <TextArea
                        value={jsonFormat(this.props.dataSource.config.headers, {
                            type: 'space',
                            size: 2
                        }) }
                        autosize={true}
                    />

                    </FormItem>
                </Form>
            </div>
        );
    }

    componentWillReceiveProps(nextProps) {

        this.setState({
            isMock: nextProps.dataSource.isMock
        })
    }
}

export  default  class MockHome extends React.Component {

    constructor() {
        super();
        this.state = {
            socketID: '',
            showQr: false,
            dataList: [],
            detailData: null,
            currentEnv: null

        };
        this.socketObj = null;
    }

    /**
     * 布局每个
     * */

    layoutMenus = () => {
        let tempList = [];
        for (let i = 0; i < this.state.dataList.length; i++) {
            let item = this.state.dataList[i];
            if (item.isMock) {
                tempList.unshift(
                    <Menu.Item key={i}><Icon type="tag"/>{item.config.url}</Menu.Item>);
            } else {
                if (item.status !== 200) {
                    tempList.unshift(
                        <Menu.Item key={i}><Icon type="frown"/>{item.config.url}</Menu.Item>);
                } else {
                    tempList.unshift(
                        <Menu.Item key={i}>{item.config.url}</Menu.Item>);
                }

            }

        }
        return tempList;
    };


    subViews = () => {
        let valueStr = "nonobankMock://" + this.state.socketID;
        if (this.state.showQr === true) {
            return <Modal
                title="扫描开始mock"
                wrapClassName="vertical-center-modal"
                visible={this.state.showQr}
                style={{top: 1}}
                footer={null}
                onCancel={() => this.setState({currentEnv: null, showQr: false})}
                maskClosable={false}
            >
                <Row type='flex' justify="center">
                    <Col span={9}>
                        <div><QRCode value={valueStr}/></div>
                    </Col>
                </Row>

            </Modal>
        }
        return <Row type='flex' justify='start'>
            <Menu
                onClick={this.handleClick}
                defaultSelectedKeys={['1']}
                defaultOpenKeys={['sub1']}
                mode="inline"
            >
                <SubMenu key="sub1" title={<span><Icon type="mail"/><span>请求结果</span></span>}>
                    {this.layoutMenus()}
                </SubMenu>

            </Menu>
            <Button type='danger' onClick={() => this.setState({dataList: [], detailData: null})}> 清除</Button>
        </Row>;
    };

    /**
     * 查看每个请求的详情
     * */
    handleClick = (e) => {
        let index = e.keyPath[0];
        let itemReq = this.state.dataList[index];
        this.setState({
            detailData: itemReq
        });
    };

    /**
     * 右边view
     * */
    rightDetail = () => {
        if (this.state.detailData) {
            return <RightDetail
                dataSource={this.state.detailData}
                mockAction={(mockRespons, open) => {
                    if (open) {
                        if (mockRespons.mockValue === undefined) {
                            ErrorModalAutoDismiss('数据不合法!!!');
                            return;
                        }
                        this.socketObj.emit('mockDataMsg', mockRespons);
                    } else {
                        this.socketObj.emit('closeMock', mockRespons);
                    }

                }
                }/>
        } else {
            return null
        }
    };

    //用户的环境选择
    userSelectEnv = () => {
        let selectEnv = this.state.currentEnv;
        if (!selectEnv) {
            InfoModal({
                title: '请选择需要mock的环境',
                content: ( <Select
                    showSearch
                    style={{width: 200}}
                    placeholder="请选择需要mock的环境"
                    optionFilterProp="children"
                    onChange={(value) => {
                        selectEnv = envObj[value];
                    }}
                >
                    <Option value="stb1">stb1</Option>
                    <Option value="stb2">stb2</Option>
                    <Option value="stb3">stb3</Option>
                    <Option value="stb4">stb4</Option>
                    <Option value="stb5">stb5</Option>
                    <Option value="stb6">stb6</Option>
                    <Option value="stb7">stb7</Option>
                    <Option value="sit">sit</Option>
                    <Option value="pre">pre</Option>
                    <Option value="pro">pro</Option>
                </Select>),

                onOk: () => {
                    if (selectEnv) {
                        this.socketObj.emit('userSelectMockEnv', selectEnv);
                        this.setState({
                            showQr: true,
                            currentEnv: selectEnv
                        });
                    } else {
                        ErrorModalAutoDismiss('请先完成环境选择')
                    }
                }
            })
        }
    };

    render() {

        if (this.state.socketID.length === 0) {
            return null;
        }
        return (<Row type="flex" justify='start'>
            {        this.userSelectEnv()}
            <Col span={8}>
                {this.subViews()}
            </Col>
            <Col span={16}>
                {this.rightDetail() }
            </Col>
        </Row>);
    }

    componentDidMount() {
        let socket = io.connect(Domain);
        this.socketObj = socket;
        socket.on('login', (socketID) => {
            console.log('连接成功会话ID为：', socketID);
            socket.id = socketID;
            this.setState({
                socketID: socketID
            });
        });

        socket.on('message', (data) => {
            console.log('message', data);
            let temp = this.state.dataList;
            temp.push(data);
            this.setState({
                dataList: temp
            })
        });

        socket.on('registDevice', (succeed) => {

            console.log('设备注册成功');
            if (succeed) {
                SuccessModal('该设备注册成功！！！')
                this.setState({
                    showQr: false
                });
            }
        });

        socket.on('disconnect', (needRefresh) => {
            if (needRefresh) {
                this.setState({
                    showQr: true
                });
            }
        });

        socket.on('mockSucced', (result) => {
            if (result) {
                SucceedModalAutoDismiss('mock成功，在对应设备重新请求即可生效', 3000)
                // this.setState({
                //     dataList: [],
                //     detailData: null
                // })
            } else {
                SucceedModalAutoDismiss('mock失败')
            }
        });

        socket.on('closeMockSucced', (result) => {
            if (result) {
                SucceedModalAutoDismiss('关闭mock成功！', 3000)
                // this.setState({
                //     dataList: [],
                //     detailData: null
                // })
            } else {
                SucceedModalAutoDismiss('关闭mock失败')
            }
        });
    }
}
